package com.zlj.proj;

import javax.crypto.spec.PSource;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Scroller;

public class ScrollView extends ViewGroup{

	public ScrollView(Context context, AttributeSet attrs){
		super(context, attrs);
		mScroller = new Scroller(context);
	}
	
	private Scroller mScroller;
	
	private int mScreenCount,mScreenIndex=0;
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		for(int i = 0; i < getChildCount(); i++){
			View view = getChildAt(i);
			LayoutParams lp = view.getLayoutParams();
			Log.i("tag", lp.height + "");
			Log.i("tag", lp.width + "");
			int width =
			        MeasureSpec.makeMeasureSpec(getMeasuredWidth(),
			                MeasureSpec.EXACTLY);
			int height =
			        MeasureSpec.makeMeasureSpec(getMeasuredHeight(),
			                MeasureSpec.EXACTLY);
			view.measure(width, height);
		}
		mScreenCount = getChildCount();
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b){
		int x = 0;
		int y = x;
		for(int i = 0; i < getChildCount(); i++){
			View view = getChildAt(i);
			view.layout(x, y, view.getMeasuredWidth(), view.getMeasuredHeight());
			x += view.getMeasuredWidth();
		}
//		scrollBy(getWidth(), 0);
	}
	
	@Override
	public void computeScroll(){ 
	   if(mScroller.computeScrollOffset()){
		   scrollBy(mScroller.getCurrX(), mScroller.getCurrY());	
		   postInvalidate();
	   }
	}
	
	public void move(int pageCount,boolean isPrev){
		mScroller.startScroll(getWidth()*mScreenIndex, 0, pageCount*(isPrev ? -getWidth() : getWidth()), 0, 3000);
		invalidate();		
	}

	public void moveToNext(){
		if(!isCanScrollNext())return;
		move(1,false);
		mScreenIndex++;
	}
	
	public void moveToPrev(){
		if(!isCanScrollPrev())return ;
		move(1,true);
		mScreenIndex--;
	}
	
	public boolean isCanScrollNext(){
		return mScreenCount-1!=mScreenIndex;
	}
	
	public boolean isCanScrollPrev(){
		return mScreenIndex!=0;
	}
	
}
